package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.factory.DAOFactory;
import com.vo.Person;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/Login")
public class LoginServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("status",0);
        jsonObj.put("info","账号不可为空");

        jsonObj.put("next","");
        if(id!=null&& !Objects.equals(id, "")){
            String password = req.getParameter("password");
            Person person = DAOFactory.getPersonDAOInstance().getPersonById(id);
            jsonObj.put("info","账号或密码错误");
            if (person != null && person.getPassword().equals(password)){
                jsonObj.put("status",1);
                jsonObj.put("info","登陆成功");
                jsonObj.put("next","/exp6/");
                req.getSession().setAttribute("uname", person.getName());
                Cookie cookie = new Cookie("uname", person.getName());
                cookie.setMaxAge(3*60*60); // cookie最多两个小时过期
                resp.addCookie(cookie);
            }
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(jsonObj.toString());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("state",0);
        jsonObj.put("info","未登录");
        String uname = (String) req.getSession().getAttribute("uname");
        if(uname!=null){
            jsonObj.put("state",1);
            jsonObj.put("info","已登录成功");
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(jsonObj.toString());
    }
}
//2017110116,谢亚飞,123
//2017130173,罗维林,123